package com.offcn.dao.Impl;

import com.offcn.dao.BaseDao;
import com.offcn.dao.UserDao;
import com.offcn.entity.User;
import com.offcn.utils.PageTool;

import java.util.List;

public class UserDaoImpl extends BaseDao<User> implements UserDao {
    @Override
    public List<User> findAllUser(PageTool page, String search) {
        String sql = "select * from user";
        if (search != null && !"".equals(search)) {
            sql = sql + " where name like '%" + search + "%'";
        }
        sql = sql + " limit ?, ?";
        return moreLine(sql, User.class, page.getStartIndex(), page.getPageSize());
    }

    @Override
    public int countUser(String search) {
        String sql = "select count(*) from user";
        if (search != null && !"".equals(search)) {
            sql = sql + " where name like '%" + search + "%'";
        }
        long count = (long) singleData(sql);
        return (int) count;
    }

    @Override
    public int addUser(User user) {
        String sql = "insert into user values(null,?,?,?,?,?,?,?,now(),?,null)";
        int dml = dml(sql, user.getName(), user.getPhone(), user.getAge(), user.getSex(), user.getUsername(), user.getPassword(), user.getStatus(), user.getRole());
        return dml;
    }

    @Override
    public User login(User user) {
        String sql = "select * from user where username = ? and password = ?";
        return singleLine(sql, User.class, user.getUsername(), user.getPassword());
    }

    @Override
    public int delAll(String arr) {
        String sql = "delete from user where uid in " + arr;
        return dml(sql);
    }

    @Override
    public int updateUser(User user) {
        String sql = "update user set name = ?, phone = ?, age = ?, sex = ?, username = ?" +
                ", password = ?, status = ?, createtime = ?, role = ? where uid = ?";
        return dml(sql, user.getName(), user.getPhone(), user.getAge(), user.getSex(), user.getUsername(),
                user.getPassword(), user.getStatus(), user.getCreatetime(), user.getRole(), user.getUid());
    }

    @Override
    public List<User> findByname(String search) {
        String sql = "select * from user ";
        if (search != null && !"".equals(search)) {
            sql += "where name like '%" + search + "%'";
        }
        return moreLine(sql, User.class);
    }

    @Override
    public User findByUid(int uid) {
        String sql = "select * from user where uid = " + uid;
        return singleLine(sql, User.class);
    }

    @Override
    public User findByPhone(String phone) {
        String sql = "select * from user where phone = ?";
        return singleLine(sql, User.class, phone);
    }

    @Override
    public int regist(String name, String phone, String password) {
        String sql = "insert into user value(null,?,?,null,null,null,?,1,now(),3,null)";
        return dml(sql,name,phone,password);
    }
}
